<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    tip: {
      type: String,
      default: ''
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData(val) {
      this.chartData = val
      this.setOptions()
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      setTimeout(() => {
        this.setOptions()
      }, 300)
    },
    setOptions() {
      this.chart.setOption({
        title: {
          text: `${this.chartData.name}(${this.chartData.total})`,
          x: 'center',
          textStyle: {
            color: '#000',
            fontSize: 14
          }
        },
        grid: {
          left: 15,
          right: 15,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          bottom: 'bottom',
          data: this.chartData.xAxis
        },
        calculable: true,
        series: [
          {
            name: this.tip,
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: this.chartData.data,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
